import logging
from logging.handlers import TimedRotatingFileHandler
import os
from src.core.config import Config
from datetime import datetime


class Logger:
    def __init__(self):
        self.debug_output = Config.DEBUG
        self.log_dir = Config.LOG_DIR
        os.makedirs(self.log_dir, exist_ok=True)
        self.logger = logging.getLogger("app_logger")
        self.logger.setLevel(logging.DEBUG)  # 设置最低日志级别为 DEBUG
        self._setup_handlers()

    def _setup_handlers(self):
        # 定义日志格式
        log_format = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        )
        # 创建流处理器
        if self.debug_output:
            stream_handler = logging.StreamHandler()
            stream_handler.setFormatter(log_format)
            stream_handler.setLevel(logging.DEBUG)
            self.logger.addHandler(stream_handler)

        # 创建时间轮转文件处理器
        for level_name in ['debug', 'info', 'warning', 'error', 'critical']:
            current_date = datetime.now().strftime("%Y-%m-%d")
            save_path = os.path.join(self.log_dir, f"app_{level_name}_{current_date}.log")
            file_handler = TimedRotatingFileHandler(
                save_path,
                when='midnight',  # 每天午夜轮转
                interval=1,
                backupCount=5
            )

            file_handler.suffix = "%Y-%m-%d"  # 文件名后缀格式
            file_handler.setFormatter(log_format)
            file_handler.setLevel(getattr(logging, level_name.upper()))
            file_handler.addFilter(self._level_filter(level_name))
            self.logger.addHandler(file_handler)

    def _level_filter(self, level_name):
        # 自定义过滤器，只允许指定级别的日志通过
        level = getattr(logging, level_name.upper())

        class LevelFilter(logging.Filter):
            def filter(self, record):
                return record.levelno == level

        return LevelFilter()

    def _log(self, level, message, model=None):
        if model:
            message = f"[{model}] {message}"
        self.logger.log(level, message)

    def debug(self, message, model=None):
        self._log(logging.DEBUG, message, model)

    def info(self, message, model=None):
        self._log(logging.INFO, message, model)

    def warning(self, message, model=None):
        self._log(logging.WARNING, message, model)

    def error(self, message, model=None):
        self._log(logging.ERROR, message, model)

    def critical(self, message, model=None):
        self._log(logging.CRITICAL, message, model)


# 创建 Logger 实例
logger_cust = Logger()
